package xuecheng.tool.api.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import lombok.extern.slf4j.Slf4j;
import xuecheng.tool.api.dto.InterceptorResultDTO;
import xuecheng.tool.json.JsonUtils;
import xuecheng.tool.json.JsonUtilsFactory;

/**
 * 自定义拦截器基类
 *
 * @author PengXueCheng
 * @version 1.0.0
 **/
@Slf4j
public abstract class BaseInterceptor implements HandlerInterceptor {

    protected JsonUtils jsonUtils = JsonUtilsFactory.obtain();

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        InterceptorResultDTO result = todoName(request);
        if (result.getIntercept()) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(jsonUtils.toJson(result));
            log.error("请求拦截|{}|{}|{}|{}", request.getMethod(), request.getRequestURL(), request.getQueryString(),
                request.getRemoteAddr());
            return false;
        }
        return true;
    }

    protected abstract InterceptorResultDTO todoName(HttpServletRequest request);

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception {

    }
}
